package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TotalFeeInfo;
import com.ruoyi.system.mapper.TotalFeeMapper;
import com.ruoyi.system.service.ITotalFeeService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static org.apache.poi.ss.util.CellUtil.getCell;

@Service
public class TotalFeeServiceImpl implements ITotalFeeService {
    private static final Logger log = LoggerFactory.getLogger(TotalFeeServiceImpl.class);


    @Autowired
    private TotalFeeMapper totalFeeMapper;

    @Override
    public void createTotalFee(String yyyyMM){
        //createNewPartition(yyyyMM);
        totalFeeMapper.deleteTotalFee(Integer.valueOf(yyyyMM));
        totalFeeMapper.createTotalFee(yyyyMM);
    }

    @Override
    public AjaxResult importTotalFeeByEtlDt(String etldt, MultipartFile file, Integer totalFeeTemplateColumnNum){
        Workbook workbook = null;
        try {
            totalFeeMapper.deleteTotalFee(Integer.valueOf(etldt));
            workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet0 = workbook.getSheetAt(0);
            int total = sheet0.getLastRowNum();
            for(int i=1;i<=total;i++){
                boolean insertFlag = true;
                Row row = sheet0.getRow(i);
                TotalFeeInfo totalFeeInfo = new TotalFeeInfo();
                UUID uuid = UUID.randomUUID();
                totalFeeInfo.setUuid(uuid.toString().replaceAll("-",""));
                totalFeeInfo.setSjfq(Integer.valueOf(etldt));
                totalFeeInfo.setFloorName("");
                totalFeeInfo.setTenantName("");
                totalFeeInfo.setOrderIndex(i);
                for(int j=0;j<totalFeeTemplateColumnNum;j++) {
                    Cell cell = getCell(row, j);
                    Object value = "";
                    if(j==1 && null == cell)
                    {
                        insertFlag = false;
                        break;
                    }
                    if(cell!=null){
                        value = getCellValue(cell);
                        if(j==1 && (null == value || StringUtils.isEmpty(value.toString().trim()))){
                            insertFlag = false;
                            break;
                        }
                        if(null != value && StringUtils.isNotEmpty(value.toString().trim())) {
                            switch (j) {
                                case 0  :  totalFeeInfo.setFloorName(value.toString()); break; //楼层
                                case 1  :  totalFeeInfo.setTenantName(value.toString()); break; //单位
                                case 2  :  totalFeeInfo.setTenantArea(Double.valueOf(value.toString())); break; //建筑面积
                                case 3  :  totalFeeInfo.setWgFee(Double.valueOf(value.toString())); break; //物管费
                                case 4  :  totalFeeInfo.setWaterNum(Double.valueOf(value.toString())); break; //水表数
                                case 5  :  totalFeeInfo.setWaterFee(Double.valueOf(value.toString())); break; //水费
                                case 6  :  totalFeeInfo.setElectricNum(Double.valueOf(value.toString())); break; //电表数
                                case 7  :  totalFeeInfo.setZhaomingNum(Double.valueOf(value.toString())); break; //实际用电，即照明电量
                                case 8  :  totalFeeInfo.setZhaomingFee(Double.valueOf(value.toString())); break; //照明费
                                case 9  :  totalFeeInfo.setDongliNum(Double.valueOf(value.toString())); break; //动力用电
                                case 10 :  totalFeeInfo.setDongliFee(Double.valueOf(value.toString())); break; //动力费
                                case 11 :  totalFeeInfo.setGongyongNum(Double.valueOf(value.toString())); break; //公用电
                                case 12 :  totalFeeInfo.setGongyongFee(Double.valueOf(value.toString())); break; //公用电费
                                case 13 :  totalFeeInfo.setKongtiaoNum(Double.valueOf(value.toString())); break; //空调电量
                                case 14 :  totalFeeInfo.setKongtiaoFee(Double.valueOf(value.toString())); break; //空调电费
                                case 15 :  totalFeeInfo.setDianfeiTotal(Double.valueOf(value.toString())); break; //电费小计
                                case 16 :  totalFeeInfo.setKongtiaoOilFee(Double.valueOf(value.toString())); break; //空调油费
                                case 17 :  totalFeeInfo.setOilTotal(Double.valueOf(value.toString())); break; //油费合计
                                case 18 :  totalFeeInfo.setFeeTotal(Double.valueOf(value.toString())); break; //合计
                            }
                        }
                    }
                }
                if(insertFlag) {
                    totalFeeMapper.insertTotalFee(totalFeeInfo);
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success("导入总费用完成。");
    }


    public void createNewPartition(String yyyyMM){
        String partitionResult = totalFeeMapper.checkPartitionExisted("p"+yyyyMM);
        if(StringUtils.isBlank(partitionResult)){
            String firstDayOfNextMonth = "";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            try {
                Date date = sdf.parse(yyyyMM+"01");
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.set(Calendar.DAY_OF_MONTH,1);
                calendar.add(Calendar.MONTH, 1);
                firstDayOfNextMonth = DateFormatUtils.format(calendar.getTime(), "yyyyMMdd").substring(0,6);
                String createPartition = "p"+yyyyMM+"  VALUES LESS THAN (" + Integer.valueOf(firstDayOfNextMonth);
                log.info(createPartition);
                totalFeeMapper.createNewTotalFeePartition(createPartition);
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private static Object getCellValue( Cell cell){
        Object value = "";
        if(cell.getCellType() == CellType.STRING){
            value = cell.getStringCellValue();
        }else if(cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
            value = cell.getNumericCellValue();
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                value = DateUtil.getJavaDate((Double) value); // POI Excel 日期格式转换
            }else{
                if ((Double) value % 1 != 0) {
                    value = new DecimalFormat("0.00").format(value);
                } else {
                    value = new DecimalFormat("0").format(value);
                }
            }
        }else if (cell.getCellType() == CellType.BOOLEAN) {
            value = cell.getBooleanCellValue();
        }
        return value;
    }
}
